//
//  GCDSocketManager.m
//  XiAnJMApp
//
//  Created by Kai Wang on 2017/5/24.
//  Copyright © 2017年 Kai Wang. All rights reserved.
//

#import "GCDSocketManager.h"
#import "DDLog.h"
#import "Tool.h"

#define SocketHost @"101.37.86.94"
#define SocketPort 50611

@interface GCDSocketManager()<GCDAsyncSocketDelegate>

@property(nonatomic,strong)NSObject * obj_Socket;


//握手次数
@property(nonatomic,assign) NSInteger pushCount;

//断开重连定时器
@property(nonatomic,strong) NSTimer *timer;

//重连次数
@property(nonatomic,assign) NSInteger reconnectCount;


@property(nonatomic,strong) NSTimer * connectTimer;


@property(nonatomic,strong) NSTimer * heartTimer;



/*
 * 端口号
 */
@property (nonatomic,strong) NSString * port;
@end

@implementation GCDSocketManager

//全局访问点
+ (instancetype)sharedSocketManager {
    static GCDSocketManager *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

//可以在这里做一些初始化操作
- (instancetype)init
{

    self = [super init];
    _obj_Socket=[NSObject new];
    if (self) {
    }
    return self;
}
-(BOOL)initS{
        //     每隔30s像服务器发送心跳包
        self.heartTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];// 在longConnectToSocket方法中进行长连接需要向服务器发送的讯息
        [self.connectTimer fire];
    
    return YES;
    
}
#pragma mark 请求连接
//连接
- (void)connectToServer {
    self.pushCount = 0;
    
    /*
     * 设置socket的代理以及代理的线程
     */
    self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    /*
     * 在设置代理之后，你需要尝试连接到相应的地址来确定你的socket是否能连通了
     */
    //host是主机地址，port是端口号
    NSError *error = nil;
    [self.socket connectToHost:SocketHost onPort:SocketPort error:&error];
    
    if (error) {
//        DLog(@"SocketConnectError:%@",error);
    }
}

#pragma mark 连接成功
//连接成功的回调
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    NSLog(@"socket连接成功----------%@-----------%hu",host,port);
    _port=[NSString stringWithFormat:@"%hu",port];
    NSLog(@"----------%hu,,,,",self.socket.localPort);
    _port=[NSString stringWithFormat:@"%hu",self.socket.localPort];

    
    [self sendDataToServer];
}


//连接成功后向服务器发送数据
- (void)sendDataToServer {
    //发送数据代码省略...
    
    //发送
    /*
     * 心跳包
     */

    //Check "|" 10位时间戳 本地MAC物理地址+“|”+本地端口号
    //Check|1495692739A860B63670A8|50613
    NSString * check=[NSString stringWithFormat:@"%@ %@ %@ %@%@%@%@",@"Check",@"|",[Tool getCurrentTimestamp],[Tool getMacAddress],@"|",_port,@"\r\n"];
    NSData *check_data=[Tool getData_from_Str:check];
    
    [self.socket writeData:check_data withTimeout:-1 tag:200];
    
    
    NSString * t1= [@"LoginBeat" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
     NSString *heart2 = [t1 stringByAppendingString:@" &\r\n"];
    

    
    NSData * test2=[Tool getData_from_Str:heart2];
                      
                      
    [self.socket writeData:test2 withTimeout:-1 tag:200];
    
    [self.socket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:10 maxLength:50000 tag:0];
    
    //读取数据
    [self.socket readDataWithTimeout:-1 tag:200];
    
//    
//    // 每隔30s像服务器发送心跳包
//    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];// 在longConnectToSocket方法中进行长连接需要向服务器发送的讯息
//    [self.connectTimer fire];
}

// 心跳连接
-(void)longConnectToSocket{
    
    
    NSString *longConnect = [[Tool  URLEncodedString:@"LoginBeat "] stringByAppendingString:@"\r&\r\n"];
    NSData   *dataStream  = [Tool getData_from_Str:longConnect];
    
    [self.socket writeData:dataStream withTimeout:-1 tag:101];
    
}


//连接成功向服务器发送数据后,服务器会有响应
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSLog(@"didReadData read data");
    NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"message is: \n%@",message);
    
    /*
     * check成功返回信息
     */
    if([message rangeOfString:@"checkrsp SUCCESS"].location !=NSNotFound){

        
        NSArray *array = [message componentsSeparatedByString:@" & "]; //从字符 & 中分隔成2个元素的数组
        NSLog(@"array:%@",array);
        NSString * checkrsp=array[1];
        NSData   *dataStream  = [Tool getData_from_Str:[NSString stringWithFormat:@"IGet %@\r\n",checkrsp]];
        
        [self.socket writeData:dataStream withTimeout:-1 tag:101];
        //读取数据
        [self.socket readDataWithTimeout:-1 tag:101];
    }
    
    /*
     * 登录成功返回信息-    loginrsp SUCCESS 2 6297be54-972f-493b-8bb2-1e2f1f7c59e1
     */
    if([message rangeOfString:@"loginrsp SUCCESS"].location !=NSNotFound){
        NSArray *array = [message componentsSeparatedByString:@" "]; //从字符 中分隔成2个元素的数组
        NSLog(@"array:%@",array);
        NSString * loginrsp=array[3];
        NSData   *dataStream  = [Tool getData_from_Str:[NSString stringWithFormat:@"IGet %@\r\n",loginrsp]];
        
        [self.socket writeData:dataStream withTimeout:-1 tag:102];
        //读取数据
        [self.socket readDataWithTimeout:-1 tag:102];
        
    }

    
    
    
    
//    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
//    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//    
//    NSError *jsonError;
//    NSDictionary *json =
//    [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
//    NSLog(@"socket - receive data %@", json);
//    
//    if (jsonError) {
//        NSLog(@"json 解析错误: --- error %@", jsonError);
//
//    }

    [self.socket readDataWithTimeout:-1 tag:200];
    
    //服务器推送次数
    self.pushCount++;
    
    //在这里进行校验操作,情况分为成功和失败两种,成功的操作一般都是拉取数据
}

#pragma mark 连接失败
//连接失败的回调
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
    NSLog(@"Socket连接失败");
    
    self.pushCount = 0;
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *currentStatu = [userDefaults valueForKey:@"Statu"];
    
    //程序在前台才进行重连
    if ([currentStatu isEqualToString:@"foreground"]) {
        
        //重连次数
        self.reconnectCount++;
        
        //如果连接失败 累加1秒重新连接 减少服务器压力
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 * self.reconnectCount target:self selector:@selector(reconnectServer) userInfo:nil repeats:NO];
        
        self.timer = timer;
    }
}

//如果连接失败,5秒后重新连接
- (void)reconnectServer {
    
    self.pushCount = 0;
    
    self.reconnectCount = 0;
    
    //连接失败重新连接
    NSError *error = nil;
    [self.socket connectToHost:SocketHost onPort:SocketPort error:&error];
    if (error) {
        NSLog(@"SocektConnectError:%@",error);
    }
}

#pragma mark 断开连接
//切断连接
- (void)cutOffSocket {
    NSLog(@"socket断开连接");
    
    self.pushCount = 0;
    
    self.reconnectCount = 0;
    
    [self.timer invalidate];
    self.timer = nil;
    
    [self.socket disconnect];
}



















- (void)socketWriteData:(NSString *)data {
    NSData *requestData = [data dataUsingEncoding:NSUTF8StringEncoding];
    [self.socket writeData:requestData withTimeout:-1 tag:0];
    [self socketBeginReadData];
}
- (void)socketBeginReadData {
    [self.socket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:10 maxLength:0 tag:0];
}





/*
 * 发送命令
 */
-(void)sendWithStr:(NSString *)str{
    
    @synchronized (_obj_Socket) {
        NSString *longConnect = [[Tool  URLEncodedString:str] stringByAppendingString:@"\r\n"];
        NSData   *dataStream  = [Tool getData_from_Str:longConnect];
        [self.socket writeData:dataStream withTimeout:-1 tag:101];
    }
    
}

/*
 * 异步
 */
-(void)Async_sendWithStr:(NSString *)str{
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //异步函数
    /*
     第一个参数:队列
     第二个参数:block,在里面封装任务
     */
    dispatch_async(queue, ^{
        [self sendWithStr:str];
        
    });

}

/*
 * 登录
 */
-(void)Action_Login{
    
    NSString *Userid=@"029008427";
    NSString *Password=@"123456";
    NSString * login=[NSString stringWithFormat:@"Login %@ %@\r\n",Userid,Password];
    
//    return "Login "+Userid+" "+Password;
//Login 029008427 123456
    NSData   *dataStream  = [Tool getData_from_Str:login];

    [self.socket writeData:dataStream withTimeout:-1 tag:101];

    
}
@end




























